<template>
    <div>

        <form action="" @submit.prevent="handlerForm">
            <input type="text" name="id" v-model.number="state.id">
            <input type="text" name="name" v-model="state.name">
            <input type="submit" value="提交">
        </form>

        <ul>
            <li v-for="(item, index) in state.arr" :key="item.id" @click="removeItem(index)">{{ item.name }}</li>
        </ul>


        <button @click="addList">添加数据</button>
    </div>
</template>

<script>

// 目标
// 掌握使用 reactive 函数包装对象为响应式数据。

// #需求
// 📝 列表渲染  、删除功能、添加功能。

import { reactive } from 'vue'

function useList () {
    const state = reactive({
        arr: [
            {
                id: 0,
                name: 'ifer',
            },
            {
                id: 1,
                name: 'elser',
            },
            {
                id: 2,
                name: 'xxx',
            },
        ],
        id: 10,
        name: ''
    })

    const removeItem = (i) => {
        // alert(i)
        state.arr.splice(i, 1)
    }
    const addList = () => {

        state.arr.push({ id: Math.random(), name: '张三' })
    }

    const handlerForm = () => {
        console.log(state.id);
        console.log(state.name);
        state.arr.push({ id: state.id, name: state.name })
        state.id = ''
        state.name = ''

    }

    return {
        state,
        removeItem,
        addList,
        handlerForm
    }
}

export default {
    setup () {

        const { state,
            removeItem,
            addList,
            handlerForm } = useList()

        return {
            state,
            removeItem,
            addList,
            handlerForm
        }

    }


}
</script>